package com.yaorange.nongjt.certificate.service.impl;

import com.yaorange.nongjt.certificate.bo.LoginUserBo;
import com.yaorange.nongjt.certificate.bo.NjtCertificateBo;
import com.yaorange.nongjt.certificate.domain.NjtUnitConfig;
import com.yaorange.nongjt.certificate.domain.NjtUserPerfect;
import com.yaorange.nongjt.certificate.domain.NjtUserRegister;
import com.yaorange.nongjt.certificate.service.INjtUnitConfigService;
import com.yaorange.nongjt.certificate.service.INjtUserPerfectService;
import com.yaorange.nongjt.certificate.service.INjtUserRegisterService;
import com.yaorange.nongjt.common.constant.NjtConstants;
import com.yaorange.nongjt.common.core.domain.entity.SysDictData;
import com.yaorange.nongjt.common.core.domain.entity.SysUser;
import com.yaorange.nongjt.common.core.domain.model.LoginUser;
import com.yaorange.nongjt.common.enums.SysUserTypeEnum;
import com.yaorange.nongjt.common.exception.ServiceException;
import com.yaorange.nongjt.common.utils.SecurityUtils;
import com.yaorange.nongjt.common.utils.nongjt.QiniuUtils;
import com.yaorange.nongjt.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @author coach tam
 * @email 327395128@qq.com
 * @values 坚持灵活 灵活坚持
 * @since 2024/10/16
 */
@Component
public class CommonService {

    @Autowired
    private INjtUserRegisterService njtUserRegisterService;
    @Autowired
    private INjtUserPerfectService njtUserPerfectService;
    @Autowired
    private ISysDictDataService sysDictDataService;

    @Value("${nongjt.uploadPath}")
    private String uploadPath;

    @Value("${nongjt.uploadType}")
    private String uploadType;

    @Transactional(readOnly = true)
    public LoginUserBo getLoginUser() {
        LoginUserBo result = new LoginUserBo();

        LoginUser sysUser = SecurityUtils.getLoginUser();
        Long userId = sysUser.getUserId();
        result.setSysUser(sysUser);

        NjtUserRegister njtUserRegister = njtUserRegisterService.selectNjtUserRegisterById(userId);
        result.setUserRegister(njtUserRegister);

        NjtUserPerfect njtUserPerfect = njtUserPerfectService.selectNjtUserPerfectById(userId);
        result.setUserPerfect(njtUserPerfect);

        return result;
    }

    @Transactional(readOnly = true)
    public List<SysDictData> queryDictType(String dictType) {
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType(dictType);
        return sysDictDataService.selectDictDataList(sysDictData);
    }


    public String upload(MultipartFile file) {
        //获取file的文件后缀
        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        String filename = UUID.randomUUID() + suffix;
        //1.保存到本地硬盘/七牛云
        if (NjtConstants.UPLOAD_TYPE_QINIU.equals(uploadType)) {
            return QiniuUtils.upload(file, filename);
        } else {
            try {
                File dic = new File(uploadPath);
                if (!dic.exists()) {
                    dic.mkdirs();
                }
                file.transferTo(new java.io.File(uploadPath + File.separator + filename));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        //2.返回文件访问路径
        return "http://localhost:8080/"+filename;
    }

    @Autowired
    private INjtUserPerfectService userPerfectService;
    @Autowired
    private INjtUnitConfigService njtUnitConfigService;
    /**
     * 根据用户，组装筛选条件 ---合格证打印列表
     * 普通用户：查看自己的
     * 监管者：查看监管范围内的
     * 管理员：查询所有
     *
     * @param njtCertificate 查询参数对象
     */
    @Transactional(readOnly = true)
    public void getAuthNjtCertificate(NjtCertificateBo njtCertificate) {
        // 获取当前登录用户
        SysUser sysUser = this.getLoginUser().getSysUser().getUser();
        String userType = sysUser.getUserType();
        if (SysUserTypeEnum.ADMIN.CODE.equals(userType)) {
            // 管理员查询所有，直接放行
            return;
        }
        if (SysUserTypeEnum.COMMON.CODE.equals(userType)) {
            // 如果是普通用户,只查看自己的
            njtCertificate.setUserId(sysUser.getUserId());
        } else if (SysUserTypeEnum.REGULATOR.CODE.equals(userType)) {
            NjtUserPerfect perfect = userPerfectService.getByRegisterUserId(sysUser.getUserId());
            // 如果是监管者,查询监管范围内的数据
            if (null == perfect.getUnitId()) {
                // 单位配置信息获取失败，无查看权限
                throw new ServiceException("单位信息获取失败，请确认所属单位是否有误");
            }
            // 监管者查询监管范围内的数据
            NjtUnitConfig unitConfig = njtUnitConfigService.selectNjtUnitConfigById(perfect.getUnitId());
            if (null == unitConfig) {
                // 单位配置信息获取失败，无查看权限
                throw new ServiceException("单位信息获取失败，请确认所属单位是否有误");
            } else {
                // 设置能查看的区域数据
                NjtUserPerfect njtUserPerfect = new NjtUserPerfect();
                njtUserPerfect.setProvince(unitConfig.getProvince());
                njtUserPerfect.setCity(unitConfig.getCity());
                njtUserPerfect.setArea(unitConfig.getArea());
                njtCertificate.setUserPerfect(njtUserPerfect);
            }
        } else {
            throw new ServiceException("无查看权限");
        }
    }
}
